//
//  HSYCustomProgressView.m
//  CustomNavigationController
//
//  Created by key on 2017/2/27.
//  Copyright © 2017年 huangsongyao. All rights reserved.
//

#import "HSYCustomProgressView.h"
#import "HSYCustomArcView+Animation.h"
#import "UIView+Frame.h"
#import <ReactiveCocoa.h>

#define PROGRESS_FILL_OFFSET_X              5
#define PROGRESS_FILL_OFFSET_Y              PROGRESS_FILL_OFFSET_X / 2

@interface HSYCustomProgressView ()

@property (nonatomic, strong) UIView *progressFillView;
@property (nonatomic, strong) UIView *progressView;
@property (nonatomic, strong) UIImageView *slideImageView;

@end

@implementation HSYCustomProgressView

- (instancetype)initWithFrame:(CGRect)frame
{
    if (self = [super initWithFrame:frame]) {
        
        self.clipsToBounds = YES;
        
        NSParameterAssert(self.height - PROGRESS_FILL_OFFSET_Y*2 > 0);
        self.progressFillView = [[UIView alloc] initWithFrame:CGRectMake(PROGRESS_FILL_OFFSET_X, PROGRESS_FILL_OFFSET_Y, self.width - PROGRESS_FILL_OFFSET_X*2, self.height - PROGRESS_FILL_OFFSET_Y*2)];
        self.progressFillView.clipsToBounds = YES;
        self.progressFillView.layer.cornerRadius = self.progressFillView.height/2;
        [self addSubview:self.progressFillView];
        
        self.progressView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, 0, self.progressFillView.height)];
        self.progressView.backgroundColor = [UIColor greenColor];
        [self.progressFillView addSubview:self.progressView];
        
        self.slideImageView = [[UIImageView alloc] initWithImage:[UIImage imageNamed:@"img_slide"]
                                                highlightedImage:[UIImage imageNamed:@"img_slide"]];
        self.slideImageView.frame = CGRectMake(0, 0, self.height, self.height);
        [self addSubview:self.slideImageView];
    }
    return self;
}

- (void)updateProgress:(CGFloat)progress
{
    _progress = progress;
    if (progress > 0) {
        @weakify(self);
        [UIView animateWithDuration:[HSYCustomArcView readDurationByValue:progress] animations:^{
            @strongify(self);
            CGFloat distance = progress * self.width;
            self.progressView.frame = CGRectMake(0, 0, distance, self.height);
            self.slideImageView.center = CGPointMake(distance + PROGRESS_FILL_OFFSET_X, self.slideImageView.center.y);
        } completion:^(BOOL finished) {
            
        }];
    }
}

- (void)setFillColor:(UIColor *)fillColor
{
    _fillColor = fillColor;
    self.progressFillView.backgroundColor = fillColor;
}

- (void)setProgressColor:(UIColor *)progressColor
{
    _progressColor = progressColor;
    self.progressView.backgroundColor = progressColor;
}

/*
// Only override drawRect: if you perform custom drawing.
// An empty implementation adversely affects performance during animation.
- (void)drawRect:(CGRect)rect {
    // Drawing code
}
*/

@end
